package com.rrd.hive.udf;

import java.util.HashMap;
import java.util.Map;

import com.weicai.caesar.CaesarUtil;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;


@Description(
        name = "mobile_operator",
        value = "_FUNC_(mobile) - Get area string from mobile or caesar encode mobile",
        extended = "Example:\n> SELECT _FUNC_('13811360000');\n  10086"
)
public class GetCarrierCode extends UDF {
    public static final Map<String, String> carrierMap = new HashMap();
    public static final String yidong = "134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,178,188,147,1705";
    public static final String liantong = "130,131,132,145,155,156,175,176,185,186,1709";
    public static final String dianxin = "133,153,173,171,177,180,181,189,1349,1700";

    static {
        for (String s : yidong.split(",")) {
            carrierMap.put(s, "10086");
        }
        for (String s : liantong.split(",")) {
            carrierMap.put(s, "10010");
        }
        for (String s : dianxin.split(",")) {
            carrierMap.put(s, "10000");
        }
    }

    public String evaluate(String[] args) throws Exception {
        if (args.length != 1) {
            throw new IllegalArgumentException("<mobile> 参数错误");
        }
        String mobile = dealMobile(args[0]);
        if (mobile == null) {
            return "unknown";
        }

        String mobilePrefix = carrierMap.containsKey(mobile.substring(0, 4)) ? mobile.substring(0, 4) : (
                carrierMap.containsKey(mobile.substring(0, 3))
                ? mobile.substring(0, 3)
                : "");
        return carrierMap.get(mobilePrefix) == null ? "unknown" : carrierMap.get(mobilePrefix);
    }

    private String dealMobile(String mobile) {
        if(mobile==null){
            return null;
        }
        if (CaesarUtil.isEncrypted(mobile)) {
            mobile = CaesarUtil.decode(mobile);
        }
        if(mobile == null || mobile.equals("") || !mobile.contains("1")){
            return  null;
        }
        String str = mobile.substring(mobile.indexOf("1"));
        if (str.length() == 11) {
            return str;
        }
        return null;
    }

    public static void main(String[] args) throws Exception {

        String[] args1 = {"FgapbbCcJ+QURb1K+4ZQg9PNtFv8fWlmVHej57Pa8XU="};
        GetCarrierCode dfu = new GetCarrierCode();
        System.out.println(dfu.evaluate(args1));
    }
}
